using System;
using System.Linq;
using System.Data;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.Serialization;
using Widgetsphere.Core.DataAccess;
using Widgetsphere.Core.Util;
using Widgetsphere.Core.Logging;
using Widgetsphere.Core.Exceptions;
using Acme.Sales;
using Acme.Sales.Business;
using Acme.Sales.Business.Objects;
using Acme.Sales.Business.Rules;
using Acme.Sales.Business.SelectCommands;
using System.IO;
using System.Data.SqlClient;

namespace Acme.Sales.Domain.Objects
{
	#region internal class
	/// <summary>
	/// This is an customizable extender for the domain class associated with the 'Customer' object collection
	/// </summary>
	[Serializable()]
	[System.ComponentModel.DesignerCategoryAttribute("code")]
	partial class DomainCustomerCollection : PersistableDomainCollectionBase, IEnumerable, ISerializable, IDisposable
	{
		#region Member Variables

		//Generated Relationships This Object Plays Parent Role


		#endregion

		#region ISerializable Members
		/// <summary>
		/// Serialization constructor
		/// </summary>
		protected DomainCustomerCollection(SerializationInfo info, StreamingContext context):this()
		{

		}

		/// <summary>
		/// Method used internally for serialization
		/// </summary>
		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{

		}
		#endregion

		#region Properties

		internal SubDomain SubDomain
		{
			get{ return (SubDomain)this.DataSet; }
		}

		internal string Modifier
		{
			get{ return SubDomain.Modifier; }
			set { SubDomain.Modifier = value; }
		}

		#endregion

		#region Contructors /Initialization

		internal DomainCustomerCollection()
		{
			try
			{
				base.TableName = "CustomerCollection";
				this.InitClass();
			}
			catch (System.Data.DBConcurrencyException dbcex) { throw new ConcurrencyException(GlobalValues.ERROR_CONCURRENCY_FAILURE, dbcex); }
			catch (System.Data.SqlClient.SqlException sqlexp) { if (sqlexp.Number == 547 || sqlexp.Number == 2627) throw new UniqueConstraintViolatedException(GlobalValues.ERROR_CONSTRAINT_FAILURE, sqlexp); else throw; }
			catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); throw; }
		}

		private void InitClass() 
		{
			BeginInit();
			this.UserIdColumn = new DataColumn("user_id", typeof(int), null, System.Data.MappingType.Element);
			base.Columns.Add(this.UserIdColumn);
			this.UserIdColumn.AllowDBNull = false;
			this.UserIdColumn.AutoIncrement = true;
			this.UserIdColumn.AutoIncrementSeed = -1;
			this.UserIdColumn.AutoIncrementStep = -1;
			this.UserIdColumn.Caption = "";
			this.RegionColumn = new DataColumn("region", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.RegionColumn);
			this.RegionColumn.Caption = "";
			this.PostalCodeColumn = new DataColumn("postal_code", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.PostalCodeColumn);
			this.PostalCodeColumn.Caption = "";
			this.PhoneColumn = new DataColumn("phone", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.PhoneColumn);
			this.PhoneColumn.Caption = "";
			this.MiddleNameColumn = new DataColumn("middle_name", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.MiddleNameColumn);
			this.MiddleNameColumn.Caption = "";
			this.LastNameColumn = new DataColumn("last_name", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.LastNameColumn);
			this.LastNameColumn.AllowDBNull = false;
			this.LastNameColumn.DefaultValue = "";
			this.LastNameColumn.Caption = "";
			this.FirstNameColumn = new DataColumn("first_name", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.FirstNameColumn);
			this.FirstNameColumn.AllowDBNull = false;
			this.FirstNameColumn.DefaultValue = "";
			this.FirstNameColumn.Caption = "";
			this.FaxColumn = new DataColumn("fax", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.FaxColumn);
			this.FaxColumn.Caption = "";
			this.CountryColumn = new DataColumn("country", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.CountryColumn);
			this.CountryColumn.Caption = "";
			this.CityColumn = new DataColumn("city", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.CityColumn);
			this.CityColumn.Caption = "";
			this.AddressColumn = new DataColumn("address", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.AddressColumn);
			this.AddressColumn.Caption = "";
			this.ModifiedByColumn = new DataColumn("ModifiedBy", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.ModifiedByColumn);
			this.ModifiedDateColumn = new DataColumn("ModifiedDate", typeof(DateTime), null, System.Data.MappingType.Element);
			base.Columns.Add(this.ModifiedDateColumn);
			this.CreatedByColumn = new DataColumn("CreatedBy", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.CreatedByColumn);
			this.CreatedDateColumn = new DataColumn("CreatedDate", typeof(DateTime), null, System.Data.MappingType.Element);
			base.Columns.Add(this.CreatedDateColumn);
			this.TimeStampColumn = new DataColumn("TimeStamp", typeof(System.Byte[]), null, System.Data.MappingType.Element);
			base.Columns.Add(this.TimeStampColumn);
			base.Constraints.Add(new UniqueConstraint("PrimaryKey", new DataColumn[] {this.UserIdColumn}, true));
			EndInit();
		}

		private bool mModifyUpdateOn = true;

		/// <summary>
		/// Raises the RowChanged event.
		/// </summary>
		protected override void OnRowChanged(DataRowChangeEventArgs e)
		{
			base.OnRowChanged(e);
			if(e.Action == DataRowAction.Change && mModifyUpdateOn)
			{
				mModifyUpdateOn = false;
				if ((e.Row[this.ModifiedByColumn] == System.DBNull.Value) || ((string)e.Row[this.ModifiedByColumn] != this.Modifier)) e.Row[this.ModifiedByColumn] = this.Modifier;
				mModifyUpdateOn = true;
			}
		}

		#endregion

		#region Database Retrieval

		internal DomainCustomer NewItem()
		{
			DomainCustomer retval = (DomainCustomer)(base.NewRow());
			((DataRow)retval)[ModifiedByColumn] = this.Modifier;
			((DataRow)retval)[ModifiedDateColumn] = DateTime.Now;
			((DataRow)retval)[CreatedByColumn] = this.Modifier;
			((DataRow)retval)[CreatedDateColumn] = DateTime.Now;
			return retval;
		}

		internal DomainCustomer NewItem(int userid)
		{
			DomainCustomer retval = NewItem();
			((DataRow)retval)["user_id"] = userid;
			return retval;
		}

		internal void AddItem(DomainCustomer item)
		{
			base.Rows.Add(item);
		}

		internal void InsertAtCustomer(DomainCustomer item, int pos)
		{
			base.Rows.InsertAt(item, pos);
		}

		internal virtual void Persist()
		{
			this.SubDomain.Persist();
		}

		#region Select Methods

		internal static DomainCustomerCollection RunSelect(string modifier)
		{
			SubDomain sd = new SubDomain(modifier);
			sd.AddSelectCommand(new CustomerSelectAll());
			sd.RunSelectCommands();
			return (DomainCustomerCollection)sd.GetDomainCollection(Collections.CustomerCollection);
		}

		internal static DomainCustomerCollection SelectByCustomerPks(List<CustomerPrimaryKey> primaryKeys, string modifier)
		{
			SubDomain sd = new SubDomain(modifier);
			sd.AddSelectCommand(new CustomerSelectByPks(primaryKeys));
			sd.RunSelectCommands();
			return (DomainCustomerCollection)sd.GetDomainCollection(Collections.CustomerCollection);
		}

		#endregion

		#endregion

		#region DomainCustomer Collection Methods
		internal void RemoveCustomer(DomainCustomer item) 
		{
			base.Rows.Remove(item);
		}

		internal virtual int Count 
		{
			get { return base.Rows.Count; }
		}

		/// <summary>
		/// Returns an enumerator that can be used to iterate through the collection.
		/// </summary>
		/// <returns>An Enumerator that can iterate through the objects in this collection.</returns>
		public virtual System.Collections.IEnumerator GetEnumerator() 
		{
			return base.Rows.GetEnumerator();
		}

		/// <summary>
		/// Gets or sets the element at the specified index.
		/// </summary>
		/// <param name="index">The zero-based index of the element to get or set. </param>
		/// <returns>The element at the specified index.</returns>
		internal DomainCustomer this[int index] 
		{
			get { return ((DomainCustomer)(base.Rows[index])); }
		}

		internal DomainCustomer GetCustomer(int userid)
		{
			return ((DomainCustomer)(base.Rows.Find(new object[] { userid })));
		}

		#endregion

		#region Data Columns Setup

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn UserIdColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn RegionColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn PostalCodeColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn PhoneColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn MiddleNameColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn LastNameColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn FirstNameColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn FaxColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn CountryColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn CityColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn AddressColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting(false)]
		public DataColumn ModifiedDateColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting(false)]
		public DataColumn ModifiedByColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting(false)]
		public DataColumn CreatedDateColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting(false)]
		public DataColumn CreatedByColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting(false)]
		public DataColumn TimeStampColumn { get; protected set; }

		#endregion

		#region Protected Overrides

		/// <summary>
		/// Create a new instance of this object type
		/// </summary>
		protected override DataTable CreateInstance()
		{
			return new DomainCustomerCollection();
		}

		/// <summary>
		/// Create new row from a DataRowBuilder
		/// </summary>
		/// <param name="builder">The DataRowBuilder object that is used to create the new row</param>
		/// <returns>A new datarow of type 'Customer'</returns>
		protected override DataRow NewRowFromBuilder(DataRowBuilder builder)
		{
			DomainCustomer retval = new DomainCustomer(builder);
			return retval;
		}

		/// <summary>
		/// Returns the type of the datarow that this collection holds
		/// </summary>
		protected override System.Type GetRowType() 
		{
			return typeof(DomainCustomer);
		}
		#endregion

		#region Implement Persistable Table Abstact Methods

		/// <summary>
		/// Gets a list of parameters for SQL update commands.
		/// </summary>
		protected override List<IDbDataParameter> GetUpdateFreeSqlParameters()
		{
			return null;
		}

		/// <summary>
		/// Gets a list of parameters for SQL insert commands.
		/// </summary>
		protected override List<IDbDataParameter> GetInsertFreeSqlParameters()
		{
			return null;
		}

		/// <summary>
		/// Gets a list of parameters for SQL delete commands.
		/// </summary>
		protected override List<IDbDataParameter> GetDeleteFreeSqlParameters()
		{
			return null;
		}

		/// <summary>
		/// Determines if the stored procedure or SQL text is used for CRUD operations.
		/// </summary>
		protected override bool UseStoredProcedure
		{
			get { return true; }
		}

		/// <summary>
		/// The stored procedure name that performs deletes for the objects in this collection
		/// </summary>
		protected override string DeleteStoredProcedureName
		{
			get { return "[dbo].[gen_CustomerDelete]"; }
		}

		/// <summary>
		/// The SQL that performs deletes for the objects in this collection
		/// </summary>
		protected override string DeleteSQLText
		{
			get { return null; }
		}

		/// <summary>
		/// The stored procedure name that performs inserts for the objects in this collection
		/// </summary>
		protected override string InsertStoredProcedureName
		{
			get { return "[dbo].[gen_CustomerInsert]"; }
		}

		/// <summary>
		/// The SQL that performs inserts for the objects in this collection
		/// </summary>
		protected override string InsertSQLText
		{
			get { return null; }
		}

		/// <summary>
		/// The stored procedure name that performs updates for the objects in this collection
		/// </summary>
		protected override string UpdateStoredProcedureName
		{
			get { return "[dbo].[gen_CustomerUpdate]"; }
		}

		/// <summary>
		/// The SQL that performs updates for the objects in this collection
		/// </summary>
		protected override string UpdateSQLText
		{
			get { return null; }
		}

		public override void SetChildSelectedFalse()
		{
		}

		/// <summary>
		/// Creates the referential integrity for this collection
		/// </summary>
		public override void CreateRelations()
		{
		}

		bool _handlingError = false;
		/// <summary>
		/// Determines if errors are handled by this object
		/// </summary>
		public override bool HandleErrors()
		{
			if (_handlingError) return false;
			_handlingError = true;
			try
			{
			return false;
			}
			catch
			{
				throw;
			}
			finally
			{
				_handlingError = false;
			}
		}
		#endregion 

		#region Helper Methods

		internal virtual string GetPrimaryKeyXml()
		{
			return GetPrimaryKeyXml(((IEnumerable<Acme.Sales.Business.Objects.Customer>)new Acme.Sales.Business.Objects.CustomerCollection(this)).Select(x => x.PrimaryKey));
		}

		internal static string GetPrimaryKeyXml(Acme.Sales.Business.Objects.CustomerPrimaryKey primaryKey)
		{
			List<Acme.Sales.Business.Objects.CustomerPrimaryKey> list = new List<Acme.Sales.Business.Objects.CustomerPrimaryKey>();
			list.Add(primaryKey);
			return GetPrimaryKeyXml(new List<Acme.Sales.Business.Objects.CustomerPrimaryKey>(list));
		}

		internal static string GetPrimaryKeyXml(IEnumerable<Acme.Sales.Business.Objects.CustomerPrimaryKey> primaryList)
		{
			StringWriter sWriter = new StringWriter();
			XmlTextWriter xWriter = new XmlTextWriter(sWriter);
			xWriter.WriteStartDocument();
			xWriter.WriteStartElement("ItemList");
			foreach(Acme.Sales.Business.Objects.CustomerPrimaryKey primaryKey in primaryList)
			{
				xWriter.WriteStartElement("Item");
				xWriter.WriteStartElement("user_id");
				xWriter.WriteString(primaryKey.UserId.ToString());
				xWriter.WriteEndElement();
				xWriter.WriteEndElement();
			}
			xWriter.WriteEndElement();
			xWriter.WriteEndDocument();
			xWriter.Flush();
			xWriter.Close();
			return sWriter.ToString();
		}

		#endregion

		#region Methods

		#endregion

		#region IDisposable Members

		void IDisposable.Dispose()
		{
		}

		#endregion

	}
	#endregion

}
